<template>
  <div class="app-container">
    <!--查询-->
    <el-row>
      <el-input style="width:200px;margin-right: 10px" v-model="tableQuery.rname" placeholder="角色名" v-perm="['role-search']"></el-input>
      <el-tooltip class="item" content="搜索" placement="top">
        <el-button icon="el-icon-search" circle @click="fetchData()" v-perm="['role-search']"></el-button>
      </el-tooltip>
    </el-row>
    <div style="margin-bottom: 30px;"></div>
    <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleCreate" v-perm="['role-insert']">{{textMap.create}}</el-button>
    <div style="margin-bottom: 30px;"></div>
    <!--列表-->
    <el-table style="width: 100%"
              :data="tableData"
              v-loading.body="tableLoading"
              element-loading-text="Loading"
              border fit highlight-current-row>
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="name" label="角色名" ></el-table-column>
      <el-table-column prop="desc" label="角色描述" ></el-table-column>
      <el-table-column prop="type_name" label="类型" ></el-table-column>
      <el-table-column prop="created_at" label="创建时间" ></el-table-column>
      <el-table-column prop="created_at" label="创建时间" ></el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-tooltip content="角色编辑" placement="top">
            <el-link icon="el-icon-edit" @click="handleUpdate(scope.$index,scope.row)" v-perm="['role-update']">编辑</el-link>
          </el-tooltip>
          <span style="margin:10px" v-perm="['role-update']">|</span>
          <el-dropdown @command="handleCommand">
            <span class="el-dropdown-link">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="{label:'menu',data:scope.row,index:scope.$index}" v-perm="['role-assign-permission']">菜单权限</el-dropdown-item>
              <el-dropdown-item :command="{label:'api',data:scope.row,index:scope.$index}" v-perm="['role-assign-permission']">接口权限</el-dropdown-item>
              <el-dropdown-item :command="{label:'delete',data:scope.row,index:scope.$index}" v-perm="['role-delete']">删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-bottom: 30px;"></div>
    <!--分页-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="tablePage.current"
      :page-sizes="[20, 30, 40, 50, 60]"
      :page-size="tablePage.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="tablePage.total">
    </el-pagination>
    <!--弹出窗口：编辑角色-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="80%">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="150px" >
        <el-form-item label="角色ID" prop="id" v-if="dialogStatus=='update'">
          <el-input v-model="temp.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色名" prop="name" >
          <el-input v-model="temp.name"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="desc">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入" v-model="temp.desc">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">创建</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
    <menu-perm :perm-map="permMap" />
    <api-perm :perm-map="permMap" />
  </div>
</template>

<script>

  import roleApi from '@/api/role'
  import { parseTime, resetTemp } from '@/utils'
  import { pageParamNames, confirm, root } from '@/utils/constants'
  import debounce from 'lodash/debounce'
  import menuPerm from './menuPerm'
  import apiPerm from './ApiPerm'

  export default {
    name: 'RoleManage',
    components:{
      menuPerm,
      apiPerm
    },
    data() {
      return {
        tableLoading:false,
        tableData: [],
        tableQuery:{
          rname: null
        },
        tablePage: {
          current: null,
          pages: null,
          size:null,
          total: null
        },
        dialogFormVisible: false,
        dialogStatus: '',
        temp: {
          idx: null,//表格的下标
          id: null,
          name: null,
          desc: null,
          type: null,
          type_name:null,
          orgnization_id: null,
          created_at:null,
          updated_at: null
        },
        permMap:{
          menuTreeShow:false,
          apiTreeShow:false,
          roleId:null
        },
        textMap: {
          update: '编辑角色',
          create: '新增角色'
        },
        rules: {
          name: [{ required: true, message: '必填', trigger: 'blur' }]
        },
      }
    },

    created(){
      this.fetchData(1)
    },

    watch:{
      //延时查询
      'tableQuery.rname': debounce( function(){
        this.fetchData()
      },500),
    },//watch

    methods: {
      parseTime,
      hasAdminRole(row){
        return row && row.rval==root.rval
      },
      //分页
      handleSizeChange(val) {
        this.tablePage.size = val;
        this.fetchData();
      },
      handleCurrentChange(val) {
        this.tablePage.current = val;
        this.fetchData();
      },
      //查询
      fetchData(page) {
        if (page)
          this.tablePage.current=page
        this.tableLoading = true
        roleApi.queryRole(this.tableQuery, this.tablePage).then(res=>{
          let roledata = res.data
          this.tableData = roledata.data
          this.tablePage.total=roledata.total
          if(!this.tablePage.current)
            this.tablePage.current=1
          if (!this.tablePage.size)
            this.tablePage.size=20
          this.tableLoading = false
        }).catch(err=>{
          this.tableData=[]
          resetTemp(this.tablePage)
          resetTemp(this.tableQuery)
          this.tableLoading=false
        })
      },
      //更新
      handleUpdate(idx,row) {
        this.temp = Object.assign({}, row) // copy obj
        this.temp.idx = idx
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => this.$refs['dataForm'].clearValidate())
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (!valid) return;
            const tempData = Object.assign({}, this.temp)//copy obj
            roleApi.updateRole(tempData).then(res => {
              tempData.updated_at = parseTime(new Date())
              this.tableData.splice(tempData.idx, 1, tempData)
              this.dialogFormVisible = false
              this.$message.success('更新角色信息成功')
            })
        })
      },
      //删除
      handleDelete(idx,row) {
        this.$confirm('您确定要永久删除该角色？', '提示', confirm).then(() => {
          roleApi.deleteRole( {id : row.id} ).then(res => {
            this.tablePage.total--
            this.dialogFormVisible = false
            const page_surplus = this.tablePage.total % this.tablePage.size
            const max_page = Math.ceil(this.tablePage.total/this.tablePage.size)
            if (!page_surplus&&this.tablePage.current>max_page)
              this.tablePage.current--
            this.$message.success("删除成功")
            this.fetchData()
          })
        }).catch(() => {
          this.$message.info('已取消删除')
        })
      },
      handleCommand(comand){
        if (comand.label==='delete'){
          this.handleDelete(comand.index, comand.data)
        }else if (comand.label==='menu'){
          this.permMap.menuTreeShow=true
          this.permMap.roleId = comand.data.id
        }else {
          this.permMap.apiTreeShow=true
          this.permMap.roleId=comand.data.id
        }
      },

      //新增
      handleCreate() {
        resetTemp(this.temp)
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => this.$refs['dataForm'].clearValidate())
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (!valid) return;
          roleApi.addRole(this.temp).then((res) => {
              this.dialogFormVisible = false
              this.$message.success('添加角色成功')
              this.fetchData(1)
            })
        })
      },
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .role-oper{
    text-decoration: underline;
    display: inline-block;
    padding: 5px;
    cursor: pointer;
  }
  .role-del{
    color: red;
  }
</style>
